<?php
class Borrow
{
	public $borrowID;
	public $userID;
	public $bookID;
	public $time;

	public function __construct()
	{
		$this->borrowID = null;
		$this->userID = '';
		$this->bookID = '';
		$this->time = '';
	}

	public static function GetBorrowByID($borrowID)
	{
		$borrow = new Borrow();
		$sql = "select * from lib_borrowInfo where info_borrow_id = $borrowID";
		$result = mysqli_query($GLOBALS['DB'], $sql);
		$row = mysqli_fetch_assoc($result);

		if(mysqli_num_rows($result) > 0){
			$borrow->borrowID = $row['info_borrow_id'];
			$borrow->userID = $row['info_user_id'];
			$borrow->userName = $row['info_user_name'];
			$borrow->bookID = $row['info_books_id'];
			$borrow->bookName = $row['info_books_name'];
			$borrow->time = $row['info_borrow_time'];

			mysqli_free_result($result);
			return $borrow;
		}else{
			return false;
		}
	}

	public static function ListBorrow($userID)
	{
		$borrowArray = new Borrow();
		$sql = "select * from lib_borrowInfo 
			where 
			info_user_id = $userID";
		$result = mysqli_query($GLOBALS['DB'], $sql);

		$bookArray = array();
		$i = 0;

		if(mysqli_num_rows($result) > 0){
			while($row = mysqli_fetch_assoc($result))
			{
				$bookArray[$i]['borrowID'] = $row['info_borrow_id'];
				$bookArray[$i]['userID'] = $row['info_user_id'];
				$bookArray[$i]['userName'] = $row['info_user_name'];
				$bookArray[$i]['bookID'] = $row['info_books_id'];
				$bookArray[$i]['bookName'] = $row['info_books_name'];
				$bookArray[$i]['time'] = $row['info_borrow_time'];
				$i++;
			}
			mysqli_free_result($result);
			return $bookArray;

		}else{
			return false;
		}
	}

	public function ToBorrow($userID, $bookID){
		$this->userID = $userID;
		$this->bookID = $bookID;

		/**
		 * Step1: 判断这本书能否借
		 */
		$sql_1 = "select lib_books_nqty
			from lib_books
			where lib_books_id = $this->bookID";
		$result = mysqli_query($GLOBALS['DB'], $sql_1);
		$row = mysqli_fetch_assoc($result);
		$flag = $row['lib_books_nqty'];

		if($flag != 0){

		 	// Step2: 向lib_borrow表添加借阅记录
			$sql_2 = "insert into lib_borrow values(
			NULL,
			'$userID',
			'$bookID',
			now()
			)";
			
			// Step3: 更新lib_books表中lib_book_nqty
			$sql_3 = "update lib_books set 
		 	lib_books_nqty = lib_books_nqty-1
		 	where
		 	lib_books_id = $bookID";

		 	// Step4: 向操作历史表添加记录
		 	$sql_4 = "insert into lib_history values (
		 		NULL,
		 		'4',
		 		'$userID',
		 		'$bookID',
		 		now()
		 		)";

		 	mysqli_query($GLOBALS['DB'], $sql_2);
		 	$this->borrowID = mysqli_insert_id($GLOBALS['DB']);
		 	
			mysqli_query($GLOBALS['DB'], $sql_3);

			mysqli_query($GLOBALS['DB'], $sql_4);

			mysqli_free_result($result);
			return $this->borrowID;

		}else{
			mysqli_free_result($result);
			return false;
		}
	}
}
?>